import time
import json

from flask import Blueprint, render_template, request, current_app, jsonify
import requests
from sqlalchemy import null
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.extensions import db
from applications.common import curd
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.rights import authorize
from applications.models import Score, PoliceModels, PsyTrainStatusModels
from applications.schemas import PoliceOutSchema, PsyTrainStatusSchema

from sqlalchemy import desc


admin_psych_realtime = Blueprint('adminPsychRealTime', __name__, url_prefix='/admin/psych_realtime')

train = null


# 实时训练


@admin_psych_realtime.get('/')
def getResultPage():
    return render_template('admin/psych/psych_realtime.html')


# 获取训练信息
@admin_psych_realtime.get('/data')
def get_result_data():
    # 获取请求参数
    user_id = request.args.get('user_id', type=int)
    user_code = request.args.get('user_code', type=str)
    user_name = request.args.get('user_name', type=str)
    user_status = request.args.get('user_status', type=int)

    # 查询参数构造
    mf = ModelFilter()
    if user_id:
        mf.exact(field_name="user_id", value=user_id)
    if user_code:
        mf.exact(field_name="user_code", value=user_code)
    if user_name:
        mf.contains(field_name="user_name", value=user_name)
    if user_status:
        mf.exact(field_name="user_status", value=user_status)
    if time:
        mf.exact(field_name="time", value=time)

    # orm查询
    # 使用分页获取data需要.items
    psytrainstatus = PsyTrainStatusModels.query.filter_by(user_status='正在训练').layui_paginate()
    count = psytrainstatus.total
    return table_api(data=model_to_dicts(schema=PsyTrainStatusSchema, data=psytrainstatus.items), count=count)


@admin_psych_realtime.get('/detail/<int:user_id>')
def main(user_id):
    status = PsyTrainStatusModels.query.order_by(desc('id')).filter_by(user_id=user_id).first()
    try:
        response = requests.post(url=current_app.config['SCENE_URL'] + '/operate/api/v1/adduser',
                                 headers={
                                     'Content-type': 'application/json'
                                 },
                                 json={
                                     "name": status.user_code,
                                     "code": status.user_name
                                 })
        data = json.loads(response.text)
        userid = data['userid']
    except:
        return fail_api('获取用户信息失败')

    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - 4))
    start_time = time_now

    response1 = requests.post(url=current_app.config['SCENE_URL'] + '/operate/api/v1/healthinfo',
                              headers={
                                  'Content-type': 'application/json'
                              },
                              json={
                                  "userid": userid,
                                  "time": start_time
                              })
    data = json.loads(response1.text)
    if len(data['data']) == 0:
        return fail_api("暂无训练数据")

    return render_template('admin/psych/psych_realtime_detail.html',
                           status=status,
                           start_time=start_time,
                           user_id=user_id,
                           data=data,
                           time_now=time_now)


@admin_psych_realtime.get('/polling2/<int:user_id>')
def ajax_polling(user_id):

    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - 4))
    start_time = time_now

    try:
        response = requests.post(url=current_app.config['SCENE_URL'] + '/operate/api/v1/healthinfo',
                                 headers={
                                     'Content-type': 'application/json'
                                 },
                                 json={
                                     "userid": user_id,
                                     "time": start_time
                                 })
        data = json.loads(response.text)

        return jsonify(data=data, time_now=time_now)
    except:
        return fail_api()


@admin_psych_realtime.post('/control/<int:status_id>')
def weather_control(status_id):
    # 创建一个tcp/ip协议的套接字
    weather = request.json
    weather = weather['weather']
    PsyTrainStatusModels.query.filter_by(id=status_id).update({'weather': weather})
    db.session.commit()
    return success_api()

@admin_psych_realtime.post('/auto_control/<int:status_id>')
def weather_auto_control(status_id):
    flag = request.json
    flag = flag['autoControl']
    PsyTrainStatusModels.query.filter_by(id=status_id).update({'control': flag})
    db.session.commit()
    return success_api()

@admin_psych_realtime.post('/start_training')
def start_training():
    # 创建一个tcp/ip协议的套接字
    user_id = request.json.get("user_id")
    user_code = request.json.get("user_code")
    user_name = request.json.get("user_name")
    user_status = request.json.get("user_status")
    time = request.json.get("time")
    psytrain = PsyTrainStatusModels(user_id=user_id, user_code=user_code, user_name=user_name, user_status=user_status,
                                    time=time)
    db.session.add(psytrain)
    db.session.commit()
    return success_api()


@admin_psych_realtime.get('/end_training/<int:user_id>')
def train_end(user_id):
    # 创建一个tcp/ip协议的套接字
    PsyTrainStatusModels.query.filter_by(user_id=user_id).update({"user_status": '未在训练'})

    db.session.commit()
    return success_api()


@admin_psych_realtime.get('/status/<int:user_id>')
def getTrainStatus(user_id):
    status = PsyTrainStatusModels.query.filter_by(user_id=user_id).order_by(desc(PsyTrainStatusModels.time)).first()
    if status is None:
        return fail_api()
    res = {
        "msg": "查询成功",
        "code": 0,
        "success": True,
        "data":
            {
                "code": status.user_code,
                "name": status.user_name,
                "status": status.user_status,
                "time": status.time,
                "weather": status.weather,
                "control": status.control
            }
    }
    return jsonify(res)
